from contextlib import contextmanager
from contextlib import closing
from urllib.request import urlopen
# -----------with语句允许我们非常方便地使用资源，而不必担心资源没有关闭---
with open("E:\\Python_Basic\\_09_IO编程\\_01_文件读写.txt", "r") as ft:
    print(ft.read())


class Query(object):

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('Begin')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            print('Error')
        else:
            print('End')

    def query(self):
        print('Query info about %s...' % self.name)


with Query("Jerry") as q:
    q.query()
# ----------------------------------Python的标准库contextlib提供了更简单的写法，上面的代码可以改写如下：---------------


class Query2(object):

    def __init__(self, name):
        self.name = name

    def query2(self):
        print("Query info about %s ." % self.name)


@contextmanager
def creat_query(name):
    print("Begin")
    qq = Query2(name)
    yield qq
    print("End")


with creat_query("Tom") as t:
    t.query2()
# --------------------在某段代码执行前后自动执行特定代码，也可以用@contextmanager-------


@contextmanager
def tag(name):
    print("<%s>" % name)
    yield
    print("</%s>" % name)


with tag("h1"):
    print("hello", end=" ")
    print("world!")

# ------------如果一个对象没有实现上下文，我们就不能把它用于with语句。这个时候，可以用closing()来把该对象变为上下文对象。
with closing(urlopen("https://www.baidu.com")) as page:
    for line in page:
        print(line)
